import "package:ducafe_ui_core/ducafe_ui_core.dart";
import "package:flutter/material.dart";
import "package:flutter_mobx/flutter_mobx.dart";
import "package:go_router/go_router.dart";
import "package:hinge/common/index.dart";
import "package:hinge/common/widgets/custom_dialog.dart";
import "package:hinge/store/root_store.dart";

class NotePage extends StatefulWidget {
  const NotePage({super.key});

  @override
  State<NotePage> createState() => _NotePageState();
}

class _NotePageState extends State<NotePage> {
  final _rootStore = RootStore();

  @override
  void initState() {
    super.initState();
    _rootStore.noteStore.loadPerfumes();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Observer(
        builder: (_) {
          if (_rootStore.noteStore.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }

          final isGuestMode = _rootStore.noteStore.isGuestMode;
          final currentUserPerfumes = _rootStore.noteStore.currentUserPerfumes;
          final otherUserPerfumes = _rootStore.noteStore.otherUsersPerfumes;

          return Container(
            decoration: BoxDecoration(
              // gradient: LinearGradient(
              //   begin: Alignment(0.50, -0.00),
              //   end: Alignment(0.50, 1.00),
              //   colors: [const Color(0xFFA794FD), const Color(0xFFFFEFFA)],
              // ),
              image: DecorationImage(
                image: AssetImage(AssetsImages.noteBg),
                fit: BoxFit.fill,
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: Column(
                children: [
                  SizedBox(height: 28.h),
                  // 标题
                  Row(
                    children: [
                      SizedBox(width: 20.w),
                      Text(
                        "Fragrance Notes",
                        style: TextStyle(
                          fontSize: 22.sp,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                      Spacer(),
                      GestureDetector(
                        onTap: () {
                          if (_rootStore.noteStore.isGuestMode) {
                            CustomDialog.show(
                              context: context,
                              title: 'Login Required',
                              content:
                                  'You need to login to release a fragrance. Would you like to login now?',
                              cancelText: 'Cancel',
                              confirmText: 'Login',
                              onConfirm: () {
                                context.push('/login').then((_) {
                                  // 从登录页面返回后刷新数据
                                  _rootStore.noteStore.loadPerfumes();
                                });
                              },
                            );
                          } else {
                            context.push('/release');
                          }
                        },
                        child: Icon(
                          IconFont.book,
                          color: Colors.white,
                          size: 28.sp,
                        ),
                      ),
                      SizedBox(width: 20.w),
                    ],
                  ),
                  SizedBox(height: 24.h),
                  // 上方横向滚动区域 - 显示当前用户香水
                  _buildCurrentUserPerfumeList(
                    currentUserPerfumes,
                    isGuestMode,
                  ),
                  SizedBox(height: 20.h),
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Padding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 12.h,
                      ),
                      child: Text(
                        "Recommend",
                        style: TextStyle(
                          fontSize: 20.sp,
                          fontWeight: FontWeight.bold,
                          color: Color(0xFF2D1457),
                        ),
                      ),
                    ),
                  ),
                  // 下方列表 - 显示其他用户香水
                  Expanded(
                    child: _buildOtherUsersPerfumeList(otherUserPerfumes),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  // 构建当前用户的香水列表（上方横向滚动）
  Widget _buildCurrentUserPerfumeList(
    List<PerfumeModel> perfumes,
    bool isGuest,
  ) {
    // 如果是游客模式，显示登录提示
    if (isGuest) {
      return Container(
        height: 337.h,
        margin: EdgeInsets.symmetric(horizontal: 20.w),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.2),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(AssetsImages.empty, width: 100.w, fit: BoxFit.cover),
              SizedBox(height: 16.h),
              Text(
                "Login to view your fragrances",
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                ),
              ),
              SizedBox(height: 8.h),
              ElevatedButton(
                onPressed: () => _handleLoginTap(context),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Color(0xFFD6C4FF),
                  foregroundColor: Colors.black,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                ),
                child: Text("Login"),
              ),
            ],
          ),
        ),
      );
    }

    // 如果用户登录了但没有香水
    if (perfumes.isEmpty) {
      return Container(
        height: 337.h,
        margin: EdgeInsets.symmetric(horizontal: 20.w),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(AssetsImages.empty, width: 100.h, fit: BoxFit.cover),
              SizedBox(height: 16.h),
              Text(
                "No notes available at the moment",
                style: TextStyle(
                  fontSize: 14.sp,
                  fontFamily: "Inter",
                  fontWeight: FontWeight.w600,
                  color: Colors.white,
                ),
              ),
            ],
          ),
        ),
      );
    }

    // 用户已登录且有香水列表
    return SizedBox(
      height: 337.h,
      child: Padding(
        padding: EdgeInsets.only(left: 15.w),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: perfumes.length,
          itemBuilder: (context, index) {
            final perfume = perfumes[index];
            final user = UserService.getUserById(perfume.userId);
            return GestureDetector(
              onTap: () {
                // 点击跳转到详情页
                context.push('/detail/${perfume.id}');
              },
              child: Container(
                width: 268.w,
                margin: EdgeInsets.only(left: 5.w, right: 5.w),
                decoration: BoxDecoration(
                  color: const Color(0xFFD6C4FF),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Column(
                  children: [
                    SizedBox(height: 10.h),
                    Stack(
                      clipBehavior: Clip.none,
                      children: [
                        ClipRRect(
                          borderRadius: BorderRadius.circular(12.r),
                          child: Image.asset(
                            perfume.url,
                            height: 248.h,
                            width: 248.w,
                            fit: BoxFit.cover,
                          ),
                        ),
                        Positioned(
                          left: 0.w,
                          right: 0.w,
                          bottom: -18.h,
                          child: Center(
                            child: CircleAvatar(
                              backgroundImage:
                                  user != null ? AssetImage(user.avatar) : null,
                              radius: 31.r,
                              backgroundColor: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),
                    Spacer(),
                    Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10.w),
                      child: Text(
                        perfume.description,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        textAlign: TextAlign.center,
                      ),
                    ),
                    SizedBox(height: 16.h),
                  ],
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  // 构建其他用户的香水列表（下方垂直列表）
  Widget _buildOtherUsersPerfumeList(List<PerfumeModel> perfumes) {
    if (perfumes.isEmpty) {
      return Center(
        child: Text(
          "No recommendations available",
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
      );
    }

    return ListView.builder(
      padding: EdgeInsets.only(bottom: 100.h),
      itemCount: perfumes.length,
      itemBuilder: (context, index) {
        final perfume = perfumes[index];
        final user = UserService.getUserById(perfume.userId);
        if (user == null) {
          return const SizedBox.shrink();
        }
        return GestureDetector(
          onTap: () {
            // 点击跳转到详情页
            context.push('/detail/${perfume.id}');
          },
          child: Container(
            margin: EdgeInsets.only(bottom: 16.h),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              child: Column(
                children: [
                  Row(
                    children: [
                      ClipRRect(
                        borderRadius: BorderRadius.circular(12.r),
                        child: Image.asset(
                          user.avatar,
                          width: 78.w,
                          height: 78.h,
                          fit: BoxFit.cover,
                        ),
                      ),
                      SizedBox(width: 16.w),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              user.nickname,
                              style: TextStyle(
                                fontWeight: FontWeight.w600,
                                color: Color(0xFF2D1457),
                                fontSize: 18.sp,
                              ),
                            ),
                            SizedBox(height: 4.h),
                            Text(
                              perfume.description,
                              style: TextStyle(
                                color: Colors.black.withOpacity(0.4),
                                fontSize: 14.sp,
                                fontFamily: "Inter",
                                fontWeight: FontWeight.w400,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                        ),
                      ),
                      SizedBox(width: 16.w),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: Color(0xFF2D1457),
                        size: 20.sp,
                      ),
                    ],
                  ),
                  SizedBox(height: 16.h),
                  Divider(color: Colors.white.withOpacity(0.15)),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  // 处理登录点击
  void _handleLoginTap(BuildContext context) {
    CustomDialog.show(
      context: context,
      title: 'Login Required',
      content:
          'You need to login to view your fragrances. Would you like to login now?',
      cancelText: 'Cancel',
      confirmText: 'Login',
      onConfirm: () {
        context.push('/login').then((_) {
          // 从登录页面返回后刷新数据
          _rootStore.noteStore.loadPerfumes();
        });
      },
    );
  }
}
